package com.david.trade.clear.tcp;

import com.david.trade.clear.component.RingBufferComponent;
import com.david.trade.clear.service.INettyService;
import com.david.trade.clear.service.TcpMessage;
import com.david.trade.clear.task.TcpMessageTask;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @author admin
 */
@Slf4j
public class TcpHandler extends SimpleChannelInboundHandler<String> implements INettyService {

    private SocketChannel socketChannel;

    public TcpHandler(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
        ChannelPipeline p = socketChannel.pipeline();
        p.addLast(new StringEncoder());
        p.addLast(new StringDecoder());
        p.addLast(this);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        log.info("服务端收到消息如下：{}", msg);
        TcpMessage tcpMessage = new TcpMessage();
        tcpMessage.setMsgId(msg.split("#")[0]);
        tcpMessage.setMsg(msg.split("#")[1]);
        tcpMessage.setTcpHandler(this);
        RingBufferComponent.ringBufferComponent.pushData(tcpMessage);
    }

    @Override
    public void reply(String msgId, String result) {
        log.info("回复客户端, msgId: {}", msgId);
        result = msgId + "#" + result;
        this.socketChannel.writeAndFlush(result);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("channelActive localaddress={},remoteaddress={}", ctx.channel().localAddress().toString(), ctx.channel().remoteAddress().toString());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("channelInactive isActive={} localaddress={},remoteaddress={}", ctx.channel().isActive(), ctx.channel().localAddress().toString(), ctx.channel().remoteAddress().toString());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

}
